import 'dart:convert';

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/http/url_helper.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/model/bank_card.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import '../../../common/utils/log_utils.dart';
import '../../../model/event/event.dart';

/// @Author lixiaobin
/// @Date 2023/12/11
/// @Description 银行卡管理
class BankCardManagePage extends StatefulWidget {
  const BankCardManagePage({super.key});

  @override
  State<BankCardManagePage> createState() => _BankCardManagePageState();
}

class _BankCardManagePageState extends State<BankCardManagePage> {
  List<BankCardModel>? _bankCardList;
  var _isEditBankCard = false;
  var _isShowRightBtn = false;

  @override
  void initState() {
    super.initState();
    App.instance.eventBus.on<BaseEvent>().listen((event) {
      if (event.tag == 'bank_card_manage') {
        _checkBankAccount();
      }
    });
    _checkBankAccount();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context, actions: _isShowRightBtn ? [_buildRightBtn()] : null),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(child: _buildPageBody()),
          const BottomWidget(),
        ],
      ),
      backgroundColor: ColorRes.colorf5f7f9,
    );
  }

  Widget _buildPageBody() {
    var isShowBankCardView = (_bankCardList?.length ?? 0) > 0;
    return isShowBankCardView ? _buildBankCardLayout() : _buildHeadLayout();
  }

  /// 添加银行卡view
  Widget _buildHeadLayout() {
    return Column(
      children: [
        GestureDetector(
            onTap: () => _loadWeb(),
            child: Container(
              height: 70.w,
              margin: EdgeInsets.all(16.w),
              width: double.infinity,
              decoration: BoxDecoration(color: ColorRes.white, borderRadius: BorderRadius.circular(4.w)),
              child: Row(
                children: [
                  SizedBox(width: 15.w),
                  ImageLoader.loadAsset('icon_add_bank.webp', 16.w),
                  SizedBox(width: 8.w),
                  Text('添加银行卡',
                      style: TextStyle(color: ColorRes.colorMain, fontSize: 17.sp, fontWeight: FontWeight.bold)),
                ],
              ),
            )),
        Expanded(child: Container())
      ],
    );
  }

  /// 添加银行卡view
  Widget _buildBankCardLayout() {
    return Container(
        height: double.infinity,
        child: ListView.builder(
            itemCount: _bankCardList?.length ?? 0,
            itemBuilder: (c, i) {
              var bankCard = _bankCardList?[i];
              var bankNum = StringUtils.formatBankNum(bankCard?.bankAccount ?? '', 4);
              return _buildBankCardItem(bankCard, bankNum);
            }));
  }

  Widget _buildBankCardItem(BankCardModel? bankCard, String bankNum) {
    return GestureDetector(
        onTap: () {
          App.instance.eventBus.fire(bankCard);
          // context.pop();
        },
        child: Container(
          width: double.infinity,
          height: 125.w,
          margin: EdgeInsets.only(top: 10.w, left: 16.w, right: 16.w),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.w)),
          child: Row(
            children: [
              Visibility(
                  visible: _isEditBankCard,
                  child: GestureDetector(
                      onTap: () {
                        _bankCardList?.forEach((element) {
                          element.isSelect = false;
                        });
                        bankCard?.isSelect = true;
                        _isShowRightBtn = true;
                        setState(() {});
                      },
                      child: Container(
                        margin: EdgeInsets.only(right: 6.w),
                        child: ImageLoader.loadAsset(
                            bankCard?.isSelect == true ? 'icon_bank_select.webp' : 'icon_bank_unselect.webp', 18.w),
                      ))),
              Expanded(
                  child: Stack(
                alignment: Alignment.topLeft,
                children: [
                  ImageLoader.loadImage(bankCard?.bankColor ?? '',
                      size: Size(double.infinity, 125.w), fit: BoxFit.fill),
                  Positioned(
                    right: 12.w,
                    child: ImageLoader.loadImage(bankCard?.bankBackground ?? '', size: Size(125.w, 125.w)),
                  ),
                  Positioned(
                      left: 15.w,
                      top: 15.w,
                      child: ImageLoader.loadImage(bankCard?.bankIcon ?? '', size: Size(27.w, 27.w))),
                  Positioned(
                      left: 50.w,
                      top: 20.w,
                      child: Text(bankCard?.openingBank ?? '',
                          style: TextStyle(color: ColorRes.white, fontSize: 15.sp, fontWeight: FontWeight.bold))),
                  Positioned(
                      left: 50.w,
                      top: 50.w,
                      child: Text(bankCard?.accountType ?? '',
                          style: TextStyle(
                            color: ColorRes.white,
                            fontSize: 13.sp,
                          ))),
                  Positioned(
                      left: 50.w,
                      bottom: 18.w,
                      child: Text(bankNum,
                          style: TextStyle(color: ColorRes.white, fontSize: 15.sp, fontWeight: FontWeight.bold))),
                  Positioned(
                    top: 15.w,
                    right: 15.w,
                    child: Visibility(
                        visible: (_bankCardList?.length ?? 0) == 1,
                        child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () => _loadWeb(replace: true),
                            child: Container(
                              padding: EdgeInsets.symmetric(vertical: 1.w, horizontal: 6.w),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(4.w),
                                  border: Border.all(color: ColorRes.white, width: 0.5)),
                              child: Text(
                                '更换',
                                style: TextStyle(color: Colors.white, fontSize: 13.sp),
                              ),
                            ))),
                  ),
                ],
              ))
            ],
          ),
        ));
  }

  /// 标题右上角 更换 按钮
  Widget _buildRightBtn() {
    return GestureDetector(
      onTap: () => _buildAlertDialog(),
      child: Container(
          margin: EdgeInsets.only(right: 16.w),
          alignment: Alignment.center,
          child: Text('解绑', style: TextStyle(color: ColorRes.colorMain, fontSize: 16.sp, fontWeight: FontWeight.bold))),
    );
  }

  /// 添加银行卡弹窗
  _buildAddBankDialog() {
    return CommWidget.buildBottomSheetDialog(context,
        title: '温馨提示',
        buildView: (c) => Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('您好，您的实名认证信息和银行卡信息不一致。请重新添加银行卡！',
                    style: TextStyle(fontWeight: FontWeight.bold, color: ColorRes.color333333, fontSize: 16.sp)),
                SizedBox(
                  height: 40.w,
                ),
                CommWidget.buildRightBtn('添加银行卡', () {
                  _loadWeb();
                  Navigator.of(c).pop();
                }),
              ],
            ));
  }

  /// 确认解绑卡弹窗
  _buildAlertDialog() {
    return CommWidget.buildBottomSheetDialog(context,
        title: '温馨提示',
        buildView: (c) => Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('请确认解绑！', style: TextStyle(color: ColorRes.color333333, fontSize: 16.sp)),
                SizedBox(
                  height: 40.w,
                ),
                Row(
                  children: [
                    Expanded(
                        child: CommWidget.buildLeftBtn('取消', () {
                      Navigator.of(c).pop();
                      context.pop();
                    })),
                    Container(width: 12.w),
                    Expanded(
                        child: CommWidget.buildRightBtn('确定', () {
                      Navigator.of(c).pop(1);
                    }))
                  ],
                ),
              ],
            )).then((value) {
      if (value == 1) {
        _unBindUserBankCard();
      } else {
        context.pop();
      }
    });
  }

  /// 添加银行卡弹窗
  _buildChooseBankDialog() {
    return CommWidget.buildBottomSheetDialog(context,
        title: '温馨提示',
        buildView: (c) => Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('仅支持绑定一张银行卡，目前您已绑定多张银行卡，请选择您需要解绑的银行卡。',
                    style: TextStyle(color: ColorRes.color333333, fontSize: 16.sp)),
                SizedBox(
                  height: 40.w,
                ),
                Row(
                  children: [
                    Expanded(
                        child: CommWidget.buildLeftBtn('取消', () {
                      Navigator.of(c).pop();
                    })),
                    Container(width: 12.w),
                    Expanded(
                        child: CommWidget.buildRightBtn('确定', () {
                      Navigator.of(c).pop(1);
                    }))
                  ],
                ),
              ],
            )).then((value) {
      if (value == 1) {
        _isEditBankCard = true;
        setState(() {});
      } else {
        context.pop();
      }
    });
  }

  /// 加载添加/替换银行卡web页面
  _loadWeb({bool replace = false}) async {
    Log.d('click _loadWeb');
    UrlHelper.loadH5Page('', "${UrlHelper.formatExecutorUrl(Api.bankCard)!}&replace=${replace ? '1' : '0'}");
  }

  /// 检查银行卡状态
  _checkBankAccount() async {
    var uId = App.instance.userInfo?.id;
    var httpRequest = HttpRequest(Api.checkBankAccountInfo, isShowLoading: false, body: {"userId": uId});
    var httpResponse = await HttpClient.post(httpRequest);
    var serviceResult = ServiceResult<bool?>.simple(httpResponse);
    if (serviceResult.success) {
      if (serviceResult.responseBody == true) {
        _walletBankCardListNew();
      } else {
        _buildAddBankDialog();
      }
    }
  }

  /// 解绑银行卡
  _unBindUserBankCard() async {
    var bankCard = _bankCardList?.firstWhereOrNull((element) => element.isSelect);
    var uId = App.instance.userInfo?.id;
    var httpRequest = HttpRequest(Api.unBindUserBankCard, isShowLoading: false, body: {
      "userId": uId,
      "bankAccount": bankCard?.bankAccount,
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var serviceResult = ServiceResult<bool?>.simple(httpResponse);
    Fluttertoast.showToast(msg: serviceResult.responseMsg ?? '');
    if (serviceResult.success) {
      _isShowRightBtn = false;
      _isEditBankCard = false;
      _walletBankCardListNew();
    }
  }

  /// 拉取银行卡信息
  _walletBankCardListNew() async {
    var uId = App.instance.userInfo?.id;
    var httpRequest = HttpRequest(Api.findBankCardByUserIdNew, body: {"userId": uId});
    print("用户id = $uId");
    var httpResponse = await HttpClient.post(httpRequest);
    var serviceResult = ServiceResult<List<BankCardModel>>.list(
        httpResponse, (list) => (list ?? []).map((e) => BankCardModel.fromJson(e)).toList());
    if (serviceResult.success) {
      _bankCardList = serviceResult.responseBody;
      if ((_bankCardList?.length ?? 0) > 1) {
        _buildChooseBankDialog();
      }
      setState(() {});
    } else {}
  }
}

class BottomWidget extends StatelessWidget {
  const BottomWidget({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('温馨提示：', style: TextStyle(color: ColorRes.color333333, fontSize: 14.sp, fontWeight: FontWeight.w500)),
            SizedBox(height: 5.w),
            Text('绑定的银行卡持卡人需与实名认证姓名一致。', style: TextStyle(color: ColorRes.color333333, fontSize: 13.sp)),
            SizedBox(height: 50.w)
          ],
        ));
  }
}
